package com.yxq.mdt.app.net;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.orhanobut.hawk.Hawk;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.modules.login.bean.UserBean;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;


/**
 * @描述 OkHttp拦截器工具类
 * @作者 yd
 * @创建日期 2019/8/27 0027 15:11
 */
public class InterceptorUtil {
    private static final String TAG = "InterceptorUtil";
    private static final String HEADER_NAME_USERID = "userId";
    private static final String HEADER_NAME_SOURCE = "source";
    private static final String HEADER_NAME_APPKEY = "appKey";
    private static final String HEADER_NAME_CHANEL = "channel_config";
    private static final String HEADER_NAME_VERSION = "appVersion";
    private static final String HEADER_NAME_LOCATION = "location";
    private static final String HEADER_NAME_PHONE_MOBILE = "phoneModel";
    private static final String HEADER_NAME_EQUIPMENT = "equipmentId";
    private static final String HEADER_KEY_TIMESTAMP = "timestamp";//客户端时间戳
    private static final String HEADER_KEY_SIGNATURE = "signature";//签名信息
    private static final String PUBLIC_KEY = "040CD66A84025B94CEAC3EC1B49C92D0";


    /**
     * 头信息处理拦截器
     * 可放一些公共参数
     *
     * @return
     */
    public static Interceptor javaCommonParamInterceptor() {
        try {
            return chain -> {
                Request request = chain.request();
                RequestBody body = request.body();
                Map<String, Object> headMap = new HashMap<>();
                if (request.method().equals("POST") && (body instanceof FormBody)) {
                    FormBody formBody = null;
                    if (body instanceof FormBody) {
                        formBody = (FormBody) body;
                        for (int i = 0; i < formBody.size(); i++) {
                            headMap.put(formBody.encodedName(i), URLDecoder.decode(formBody.encodedValue(i), "UTF-8"));
                        }
                    }
                    Request.Builder newBuilder = request.newBuilder();
                    if (BuildConfig.DEBUG) {
                        Log.e("JAVA-POST", JSON.toJSONString(headMap));
                    }
                    RequestBody bodyJson = RequestBody.create(JSON.toJSONString(headMap), MediaType.parse("application/json; charset=utf-8"));
                    Request newRequest = newBuilder.method(request.method(), bodyJson).build();

                    return chain.proceed(newRequest);
                }
                return chain.proceed(request);
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Interceptor javaFormCommonParamInterceptor() {
        return chain -> {
            Request request = chain.request();
            RequestBody body = request.body();
            Map<String, Object> headMap = new HashMap<>();
            if (request.method().equals("POST") && (body instanceof FormBody)) {
                FormBody formBody = null;
                if (body instanceof FormBody) {
                    formBody = (FormBody) body;
                    for (int i = 0; i < formBody.size(); i++) {
                        headMap.put(formBody.encodedName(i), URLDecoder.decode(formBody.encodedValue(i), "UTF-8"));
                    }
                }
                Request.Builder newBuilder = request.newBuilder();
                if (BuildConfig.DEBUG) {
                    Log.e("JAVA-POST", JSON.toJSONString(headMap));
                }
                RequestBody bodyJson = RequestBody.create(JSON.toJSONString(headMap), MediaType.parse("multipart/form-data; charset=utf-8"));
                Request newRequest = newBuilder.method(request.method(), bodyJson).build();

                return chain.proceed(newRequest);
            }
            return chain.proceed(request);
        };
    }

    /**
     * 头信息处理拦截器
     * 可放一些公共参数
     *
     * @return
     */
    public static Interceptor phpCommonParamInterceptor() {
        try {
        return chain -> {
            Request request = chain.request();
            RequestBody body = request.body();
            Map<String, String> headMap = new HashMap<>();
            if (request.method().equals("POST")) {
                if ("multipart".equals(body.contentType().type())) {
                    return chain.proceed(request);//上传文件直接返回 不做处理
                }
                if (body instanceof FormBody) {
                    FormBody formBody = (FormBody) body;
                    for (int i = 0; i < formBody.size(); i++) {
                        headMap.put(formBody.encodedName(i), URLDecoder.decode(formBody.encodedValue(i), "UTF-8"));
                    }
                }
                UserBean userBean = Hawk.get(SPKey.SP_KEY_USER_INFO);
                headMap.put("access_token", userBean != null ? userBean.getAccess_token() : "");
                Request.Builder newBuilder = request.newBuilder();
                FormBody formBody = createNewFormBody(headMap);
                if (BuildConfig.DEBUG) {
                    Log.e("PHP-POST", JSON.toJSONString(headMap));
                }
//                RequestBody bodyJson = RequestBody.create(JSON.toJSONString(headMap), MediaType.parse("application/json; charset=utf-8"));
                Request newRequest = newBuilder.method(request.method(), formBody).build();
                return chain.proceed(newRequest);
            }
            return chain.proceed(request);
        };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static FormBody createNewFormBody(Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (!TextUtils.isEmpty(key)) {
                builder.addEncoded(key, value);
            }
        }
        return builder.build();
    }

    private static String getParamStr(Map<String, String> headMap) {
        StringBuilder sb = new StringBuilder();
        Iterator<String> iterator = headMap.keySet().iterator();
        List<String> keyList = new ArrayList<>();
        while (iterator.hasNext()) {
            keyList.add(iterator.next());
        }
        Collections.sort(keyList);
        for (String key : keyList) {
            if (!key.startsWith("text") && !key.startsWith("file") && !key.startsWith("unSign")) {
                try {
                    String value = headMap.get(key);
                    if (!TextUtils.isEmpty(value)) {
                        continue;
                    }
                    sb.append(key).append("=").append(value).append("&");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}
